const { getOrderInfo } = require('../../model/order')
const fs = require('fs')
// 引入支付模块
const AlipaySdk = require('alipay-sdk').default
const AlipayFormData = require('alipay-sdk/lib/form')

//支付宝支付返回form表单
const alipay = async (req, res) => {
	const output = { code: 200, msg: '操作成功' }
	// 获取支付基本参数  子订单交易号 总支付金额
	let { outTradeNo, type } = req.body;
	// 验证基本参数
	if (!outTradeNo || (type != 1 && type != 2)) {
		output.code = 500;
		output.msg = "参数错误:缺少支付参数outTrade或者type";
		return res.send(output);
	}
	// 通过订单号获取金额
	const { description, total_amount: totalAmount } = await getOrderInfo({ out_trade_no: outTradeNo })
	if (!totalAmount) {
		output.code = 500;
		output.msg = "订单信息不存在";
		return res.send(output);
	}
	// 初始化插件
	const alipaySdk = new AlipaySdk({
		//此处使用的是沙箱环境
		appId: '9021000140697146',
		// 最新网关地址 https://openapi-sandbox.dl.alipaydev.com/gateway.do
		// 之前的网关地址: https://openapi.alipaydev.com/gateway.do
		gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do',
		signType: 'RSA2', // 注意这里默认是RSA2， 正常不要配置
		privateKey: 'MIIEogIBAAKCAQEAg4qjBgA+pNTAI4z2i//ycuckd0diSorWkSkspVz1TG9mZ8Qs84Me3zI4BeSXjj95HpSJB8id4LYLGGB6iunRYHt6Nu4BtrgbttjNVViped6XKYllOTCGLThYUkucN2/cA4FEcgYGmEdFR/frA2mjR/kgSS4QhBEmwcBWHn3rbDNxeIfAKXvZHOALLc1FYaOGi8jBjxcmDTKXCzw/kjOiFLX6beZOKw6bXsybBh6yq5dThf3yFmC5TUpxqF5F08vKpOruTuehJT4ipPY2ySJFYsmdMC53hcatxooRGYF+Y4MBWgv4vbEQNRmfeFjKRFEiTml1MhuBm50zZptCrPYuPQIDAQABAoIBABQn2BcBTpf/KXnJDbYh/8pvdHz6aSs23u3bO0YTWlrd7vkTbDfb7Y0RqtfsUPSw8SQoal7Q9LAL9ONFVUGX1kdMZEuqaITQ7R41VjEvprhPzSXGMcZzkvu22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isjX+GIBWcoPZA=',
		alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg4qjBgA+pNTAI4z2i//ycuckd0diSorWkSkspVz1TG9mZ8Qs84Me3zI4BeSXjj95HpSJB8id4LYLGGB6iunRYHt6Nu4BtrgbttjNVViped6XKYllOTCGLThYUkucN2/cA4FEcgYGmEdFR/frA2mjR/kgSS4QhBEmwcBWHn3rbDNxeIfAKXvZHOALLc1FYaOGi8jBjxcmDTKXCzw/kjOiFLX6beZOKw6bXsybBh6yq5dThf3yFmC5TUpxqF5F08vKpOruTuehJT4ipPY2ySJFYsmdMC53hcatxooRGYF+Y4MBWgv4vbEQNRmfeFjKRFEiTml1MhuBm50zZptCrPYuPQIDAQAB'
	});
	const formData = new AlipayFormData()
	// 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
	// formData.setMethod('get')
	// 配置回调接口
	//异步通知地址，需要配置内网穿透(钉钉)
	formData.addField('notifyUrl', 'http://aslegou.vaiwan.com/front/alipay/notifyUrl')
	//同步通知地址
	formData.addField('returnUrl', 'http://localhost:8080/#/orderList')
	// 设置参数
	formData.addField('bizContent', {
		outTradeNo,
		productCode: 'FAST_INSTANT_TRADE_PAY',
		totalAmount,
		subject: '商品',
		body: '商品详情',
	});

	// 根据请求type类型获取请求支付form表单 1是返回手机网站支付 2是返回pc端网站支付
	let payUrl = type == 1 ? 'alipay.trade.page.pay' : 'alipay.trade.wap.pay'
	// 请求接口
	const result = await alipaySdk.pageExec(
		payUrl,
		{},
		{ formData: formData },
	);
	output.data = result
	res.send(output);
}


// 异步回调地址: 支付平台一般会多次请求(8次), 直到响应了'success'
const alipayNotifyUrl = async (req, res) => {
	const output = { code: 200, msg: 'success' }
	const payload = req.body
	// 记录异步日志
	fs.writeFileSync(`./alipay.log`, JSON.stringify(payload))
	res.send(output.msg);
}

module.exports = {
	alipay, alipayNotifyUrl
}